Auth
This article will show you how to create a basic Auth
decorator helping you prevent unauthenticated user from accessing your service.
#
1. Auth decoratorPseudo code 1:
import { Injectable } from '@cellularjs/di';import { ServiceHandler, IRQ, NextHandler, addServiceProxies } from '@cellularjs/net';
@Injectable()class AuthProxy implements ServiceHandler { constructor( private irq: IRQ, private nextHandler: NextHandler, ) { }
async handle() { const { irq, nextHandler } = this;
if (!irq.header.accessToken) { throw new UnAuthorized(); }
const payload = parseJwt(irq.header.accessToken); if (!payload) { throw new UnAuthorized(); }
return nextHandler.handle(); }}
export const Auth = () => service => { addServiceProxies(service, [AuthProxy]);
return service;}
@Auth()@Service({ scope: 'publish' })export class YourProtectedService { // ...}
Pseudo code 2: allow client to get current logged-in user data.
import { Injectable } from '@cellularjs/di';import { ServiceHandler, IRQ, NextHandler, addServiceProxies } from '@cellularjs/net';
// Use a class as a token for resolving sign-in user data later.class SignInUser {}
@Injectable()class AuthProxy implements ServiceHandler { constructor( private irq: IRQ, private nextHandler: NextHandler, ) { }
async handle() { const { irq, nextHandler } = this;
if (!irq.header.accessToken) { throw new UnAuthorized(); }
const payload = parseJwt(irq.header.accessToken); if (!payload) { throw new UnAuthorized(); }
const extModule = nextHandler.getExtModule(); await extModule.addProvider({ token: SignInUser, useFunc: async () => await UserModel.find(payload.userId), cycle: 'permanent', });
return nextHandler.handle(); }}
@Auth()@Service({ scope: 'publish' })export class YourProtectedService { constructor( private signInUser: SignInUser, ) { }
// ...}